package io.renren;

import io.renren.datasources.DynamicDataSourceConfig;
import org.apache.jmeter.DynamicClassLoader;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Import;

import java.net.URL;
import java.util.Collections;
import java.util.List;


@SpringBootApplication(exclude =
        {DataSourceAutoConfiguration.class,
                MongoAutoConfiguration.class, MongoDataAutoConfiguration.class})
@Import({DynamicDataSourceConfig.class})
public class RenrenApplication extends SpringBootServletInitializer {

    /** The class loader to use for loading JMeter classes. */
    private static final DynamicClassLoader loader;

    static {
        loader = createClassLoader(Collections.emptyList());
    }

    public static void main(String[] args) {
        Thread.currentThread().setContextClassLoader(loader);

        SpringApplication.run(RenrenApplication.class, args);
    }

    /**
     * 动态加载jmeter目录下的jar包
     * @param jars
     * @return {@link DynamicClassLoader }
     * @author pengzhikang
     * @date 2023/03/21 09:46
     */
    private static DynamicClassLoader createClassLoader(List<URL> jars) {
        ClassLoader parentLoader = Thread.currentThread().getContextClassLoader();
        return java.security.AccessController.doPrivileged(
                (java.security.PrivilegedAction<DynamicClassLoader>) () ->
                        new DynamicClassLoader(jars.toArray(new URL[0]), parentLoader)
        );
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(RenrenApplication.class);
    }
}
